<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\dao\setting;

use app\dao\BaseDao;
use app\model\setting\SystemConfig;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SystemConfigDao extends BaseDao
{
    /**
     * 设置模型
     * @return string
     */
    protected function setModel(): string
    {
        return SystemConfig::class;
    }

    /**
     * 获取某个系统配置
     */
    public function getSysConfigValue(string $key)
    {
        return $this->search(['key' => $key])->value('value');
    }

    /**
     * 获取多个所需配置
     * @param array $key
     * @return mixed
     */
    public function getSysConfigAll(array $key = []): mixed
    {
        if (!empty($key)) {
            return $this->search(['key' => $key])->column('value', 'key');
        } else {
            return $this->getModel()->column('value', 'key');
        }
    }

    /**
     * 保存系统配置
     * @param string $groupName
     * @param string $key
     * @param string $v
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveSystemConfig(string $groupName, string $key, string $v): bool
    {
        $sysConfigQuery = $this->find([['key', '=', $key]]);
        if ($sysConfigQuery) {
            $sysConfigQuery->group_name = $groupName;
            $sysConfigQuery->value = $v;
            $sysConfigQuery->save();
        } else {
            $this->save(['group_name' => $groupName, 'key' => $key, 'value' => $v]);
        }

        return true;
    }
}
